<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*,java.lang.reflect.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.model.pojo.*,com.tianxiabuyi.model.*,com.tianxiabuyi.utils.*,java.util.concurrent.*,com.tianxiabuyi.Input,com.tianxiabuyi.Message"%>
<%@ page import="com.tianxiabuyi.persist.Where" %>
<%@ page import="com.tianxiabuyi.persist.QBuilder" %>
<%@ page import="com.tianxiabuyi.persist.DBTools" %>
<%@ include file="errcode.jsp"%>
<%@ include file="characterfilter.jsp"%>
<%@ page import="com.alibaba.fastjson.*" %>

<%!
	static final Integer EXPIRES_IN = 3600; // token有效时间(秒)

	// 问卷题型
	static final Integer SURVEY_QUESTION_TYPE_PARENT = 0; // 副标题
	static final Integer SURVEY_QUESTION_TYPE_SINGLE = 1; // 单选题
	static final Integer SURVEY_QUESTION_TYPE_MULTI = 2; // 多选题
	static final Integer SURVEY_QUESTION_TYPE_INPUT = 3; // 填空题
	static final Integer SURVEY_QUESTION_TYPE_GRADE = 4; // 打分题
	static final Integer SURVEY_QUESTION_TYPE_MUTILINPUT = 5; // 多重填空题
	static final Integer SURVEY_QUESTION_TYPE_MUTILINPUT_CHILD = 6; // 多重填空题子题目
	// 问卷分类
	static final Integer SURVEY_CATEGORY_COMMON = 1; // 模板
	static final Integer SURVEY_CATEGORY_FOLLOW = 2; // 复诊随访
	static final Integer SURVEY_CATEGORY_QUESTION = 3; // 问卷随访
	static final Integer SURVEY_CATEGORY_GRADE = 4; // 满意度调查

	// 时间轴类型
	static final Integer TIME_LINE_OPERATE = 1; // 手术类型
	static final Integer TIME_LINE_FOLLOW = 2; // 复诊随访类型
	static final Integer TIME_LINE_QUESTION = 3; // 问卷随访类型
	static final Integer TIME_LINE_OTHER = 4; // 其他类型

	// 设备类型
	static final Integer CLIENT_IOS = 1;
	static final Integer CLIENT_ANDROID = 2;
	static final Integer CLIENT_WECHAT = 3;

	// 预约服务状态
	static final Integer STATE_ADD = 1; // 新增
	static final Integer STATE_HANDLED = 2; // 处理未做
	static final Integer STATE_OVER = 3; // 已做
	static final Integer STATE_ADD_CANCEL = 4; // 新增取消
	static final Integer STATE_HANDLED_CANCEL = 5; // 处理取消
	static final Integer STATE_HANDLED_PASS = 6; // 处理过期

	// 可见性
	static final Integer STATUS_ENABLE = 1; // 可见
	static final Integer STATUS_DISABLE = 0; // 不可见

	// 用户类型
	static final Integer USER_PATIENT = 100;   // 普通用户
	static final Integer USER_EMPLOYEE = 200;  // 医院员工
	static final Integer SIGN_PATIENT = 300;   // 签约用户
	static final Integer SIGN_EMPLOYEE = 400;  // 签约医生

	// 亲情账号
	static final Integer SELF = 0;   // 本人
	static final Integer FAMILY = 1;  // 家属

	// 付款状态
	static final Integer WAIT_PAY = 0;   // 等待付款
	static final Integer ALREADY_PAY = 1;   // 已付款
	static final Integer BACK_PAY = 2;   // 退款
	static final Integer PASS_PAY = 3;   // 过期

	// 科室介绍表中type字段
	static final Integer DEPT_ALL = 1; // 科室介绍和专家介绍中都显示
	static final Integer EXPERT_INTRODUCTION = 2; // 只在专家介绍中显示
	static final Integer DEPT_INTRODUCTION = 3; // 只在科室介绍中显示,院内版用户
	static final Integer DEPT_ENROLL = 4; // 继教报名中大科和单元
	static final Integer DEPT_ORDINARY = 5; // 排班中普通号里的科室
	static final Integer DEPT_EXPERT = 6; // 排班中专家号里的科室
	static final Integer DEPT_EXAM = 7; // 考试科室
	static final Integer DEPT_CONTACT = 8; // 通讯录科室
	static final Integer DEPT_REGISTER = 9; // 挂号普通专家一起返回

	// 挂号类型
	static final Integer ORDINARY_NO = 1; // 普通号
	static final Integer EXPERT_NO = 2; // 专家号

	// 通知类型
	static final Integer CRITICAL_VALUES = 1; // 危急值
	static final Integer AFFAIR_NOTIFICATION = 2; // 事务通知
	static final Integer PATIENT_NOTIFICATION = 3; // 通知患者

	// 默认头像
	static final String USER_AVATAR_M = "http://image.eeesys.com/default/user_m.png";      // 男性用户
	static final String USER_AVATAR_FM = "http://image.eeesys.com/default/user_fm.png";     // 女性用户
	static final String EMPLOYEE_AVATAR_M = "http://image.eeesys.com/default/doctor_m.png";  // 男性医生
	static final String EMPLOYEE_AVATAR_FM = "http://image.eeesys.com/default/doctor_fm.png"; // 女性医生
	static final String DEFAULT_AVATAR = "http://image.eeesys.com/default/default_avatar.png"; // 默认头像

	// 发送邮件
	void mail(String title, String content) {
		String url = "http://cloud.eeesys.com/mail/send.php";
		Map<String, String> param = new HashMap<String, String>();
		param.put("to", "yangh@eeesys.com");
		param.put("title", title);
		param.put("content", content);
		String str = HttpUtil.post(url, param);
	}

	// 抓取数据出问题时发邮件
	void mail(String title) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String now = sdf.format(new Date());
		mail(now + ":" + title, "");
	}
	
	// 替换html中特殊字符
	String replaceHtml(String content) {
		if (content==null) return "";
		String html = content;
		html = html.replaceAll( "\"", "&quot;");
		html = html.replaceAll("\t","").replaceAll("\n","").replaceAll("\r","");
		html = html.replaceAll("<v:imagedata[^>]*?>", "</v:imagedata>");
		return html;
	}

  // 判断对象是否为空
	boolean isEmpty(Object o) {
		if (o == null) {
			return true;
		}
		String type = o.getClass().getName();
		if ("java.lang.String".equals(type)) {
			String result = (String)o;
			return result.trim().length() == 0;
		} else if (type.startsWith("java.util.") && type.endsWith("List")) {
			List result = (List)o;
			return result.size() == 0;
		} else if (type.startsWith("java.util.") && type.endsWith("Map")) {
			Map result = (Map)o;
			return result.size() == 0;
		} else if (type.startsWith("[")) {
			return Array.getLength(o) == 0;
		}
		return false;
	}

	String dateToStr(long time, String unit) {
		String[] units = {"year", "month", "day", "hour", "minute", "second"};
		String[] cunits = {"年", "月", "日", "小时", "分钟", "秒"};
		long[] divs = {365 * 24 * 3600 * 1000L, 30 * 24 * 3600 * 1000L, 24 * 3600 * 1000L, 3600 * 1000L, 60 * 1000L, 1000L};
		long[] zdivs = {12, 30, 24, 60, 60};
		int i = 0;
		for (int j = 0; j < units.length; j++) {
			if (units[j].equals(unit)) {
				i = j;
				break;
			}
		}
		long result = time / divs[i];
		if (Math.abs(result) != 0) {
			if (--i >= 0) {
				if (Math.abs(result) / zdivs[i] != 0) {
					if (i < 0) {
						return "转换失败";
					}
					return dateToStr(time, units[i]);
				}
			}
			long ys = 0;
			if (i + 1 <= units.length) {
				ys = time % divs[i+1];
			}
			if (ys > 0 && i > 0)
				++result;
			return result + cunits[i + 1];
		} else {
			if (++i >= units.length)
				return "转换失败";
			return dateToStr(time, units[i]);
		}
	}

	// 竖线分割的字符串转list
	List<String> stringToList(String str) {
		List<String> list = new ArrayList<String>();
		if (!isEmpty(str)) {
			String[] strs = str.split("\\|");
			for (int  i = 0; i < strs.length; i++) {
				list.add(strs[i]);
			}
		}
		return list;
	}

	// 返回多少天之前或之后
	public static String before(String date, int num) {
		try {
			Date d = DateUtil.parseDate(date);
			return DateUtil.formatDate(DateUtil.afterNDay(d, num));
		} catch (Exception e) {
			return date;
		}
	}
	
	// 获取用户头像，如没有则根据用户类型设置默认头像
	public String getDefaultAvatar(User user) {
		 if (user == null)
			 return USER_AVATAR_M;
		 String avatar = user.getAvatar();
		 if (user.getAvatar() !=  null)
			 return avatar;
		 Integer type = user.getType() == null?USER_PATIENT:user.getType();
			Integer gender = user.getGender()== null?1:user.getGender();
		 if (type.equals(USER_PATIENT) && gender == 1)
			 return USER_AVATAR_M;
		 else if (type.equals(USER_PATIENT) && gender == 0)
			 return USER_AVATAR_FM;
		 else if (type.equals(USER_EMPLOYEE) && gender == 1)
			 return EMPLOYEE_AVATAR_M;
		 else
			 return EMPLOYEE_AVATAR_FM;
	 }
	
		
	// 获取用户显示的名称
	public String getDisplayName(User user) {
		if (user == null)
			return "暂无";
		String userName = Tools.getDesc(user.getUserName(), "");
		String nickName = Tools.getDesc(user.getNickName(), "");
		String name = Tools.getDesc(user.getName(), "");
		Integer type = user.getType() == null?USER_PATIENT:user.getType();
		if (type.equals(USER_PATIENT)) {
			return ((nickName!= null) && (nickName.length() > 0)) ? nickName : userName;
		}
		return name.length() > 0 ? name:userName;
	}
	
	// 补充医院信息
	void completeHospitalInfo(List<Map> list) {
		String hospitals = "-1";
		for (Map map:list) {
			hospitals += "," + Tools.getDesc(map.get("hospital"), "-1");
		}
		List<Hospital> hospitalList = QBuilder.db("basedb").select().from("Hospital").where(new Where("hospital in(" + hospitals + ")")).query().getResultObj();
		Map<Integer, String> mapHospital = new HashMap<Integer, String>();
		for (Hospital hospital:hospitalList) {
			mapHospital.put(hospital.getHospital(), hospital.getName());
		}
		for (Map map:list) {
			map.put("hospital_name", Tools.getDesc(mapHospital.get(Tools.getInt(map.get("hospital") + "")), "未知医院"));
		}
	}
	
	// 手机号验证
    public static boolean isChinaPhoneLegal(String str)   {
		if (str == null)
			return false;
        //String regExp = "^((13[0-9])|(14[5,7])|(15[0-9])|(17[3,6-8])|(18[0-9]))\\d{8}$";
		String regExp = "^1[3456789]\\d{9}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
	
	// 中文姓名验证
    public static boolean isChinaNameLegal(String name)   {
		if (name == null)
			return false;
      //  String regexStr = "^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$";
		String regexStr = "^[\\u4E00-\\u9FA5A-Za-z0-9_.%&',;=?$\\x22]{2,20}$";
		if (!name.matches(regexStr)) {
			return false;
		}
		if (name.length() > 20 || name.length() < 2 ) {
			return false;
		}
		return true;
    }
	
	// 生成用户名
    public static String generateUserName(String str)   {
		if (str.length() > 20)
			str = "txby";
        int max = 1000;
		int min = 1;
		Random random = new Random();
		int s = random.nextInt(max)%(max-min+1) + min;
        return ("txby" + System.currentTimeMillis() + s + str);
    }
	
	// 判断天下专家是否有查看患者报告的权限
    public  boolean validateReportAuth(Token token, Integer patientUid)   {
		List authList = QBuilder.db("basedb").select().from("OperateHistory as o").where(new Where("o.hospital=", token.getHospital()).and("o.category=", 8).and("o.operate=", 7).and("o.status=", STATUS_ENABLE).and("o.uid=", patientUid).and("o.oid=", token.getUid())).query().getResultObj();
		if (isEmpty(authList))
			return false;
		return true;
    }
	
	// 	获取n天之后(n为正)或之前(n为负)的日期
	public static String getNDays(int n)   {
		  Calendar calendar = Calendar.getInstance();
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		  calendar.add(Calendar.DATE, n);
		  return sdf.format(calendar.getTime());
	}
	
	// 	获取n天之后(n为正)或之前(n为负)的日期
	public static String getNDays(int n,String fmt)   {
		  Calendar calendar = Calendar.getInstance();
		  SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		  calendar.add(Calendar.DATE, n);
		  return sdf.format(calendar.getTime());
	}
	
	final static int DEFAULT_DATA_INTERVAL = 15; // 默认的日期间隔 不含当天  1113医院获 以下接口使用： 1.取普通门诊预约信息和专家列表  2.获取某个专家的预约信息  3.v3\schedule\date.jsp

	// 1113医院接口前置机地址(请修改成所发布环境相对应的地址)
	static final String HOST_BASE_URL_1113 = "http://localhost:8080";
%>
<%
	Input input = new Input(request); // 请求对象
	Integer hospital = input.getInt("hospital", -1); // 医院id
	String act = input.getDesc("act", "list"); // 访问类型
	// 生成log
	String path = Tools.getDesc(input.getPath(), "");
	if (path.startsWith("/v3/")) {
		String useragent = Tools.getDesc(input.getUseragent(), "");
		String params = Tools.getDesc(input.getParams(), "");
		String ip = input.getIp();
		String[] p = params.split("&");
		String appType = "";
		String hospitalStr = "";
		for (int i = 0; i < p.length; i++) {
			String value = p[i];
			if (value.startsWith("hospital")) {
				hospitalStr = value.replace("hospital=", "");
			}
			if (value.startsWith("app_type")) {
				appType = value.replace("app_type=", "");
			}
		}
		HashMap logMap = new HashMap();
		logMap.put("ipv4", ip);
		logMap.put("hospital", hospitalStr);
		logMap.put("app_type", appType);
		logMap.put("create_time", System.currentTimeMillis());
		logMap.put("useragent", useragent);
		logMap.put("params", params);
		logMap.put("url", path);
		DBTools.db("basedb").addItem("sys_log", logMap);
	}
%>
